package subumbo.micro.controller
{
	import flash.utils.Dictionary;
	
	import subumbo.micro.controller.ApplicationEvent;
	import subumbo.micro.controller.EventCentre;
	import subumbo.micro.view.Image;
	
	
	public class ImageManager
	{
		private var _refs:Array;
		private var _numImages:int;
		private var _loadCount:int;
		
		public function init(numImages:int = 1):void
		{ 	
			_numImages = numImages;
			_refs = [];
		}
		
		public function addImage(image:Image):void
		{
			_refs.push(image);
			if(_refs.length == _numImages)
			{
				_refs.sortOn("priority");
				loadImage();
			}
		}
		
		private function loadImage():void
		{
			var image:Image = Image(_refs[_loadCount]);
			image.addEventListener(ImageEvent.IMAGE_LOADED, onImageLoaded, false, 0, true);
			image.startLoading();
		}
		
		private function onImageLoaded(e:ImageEvent):void
		{	
			e.target.removeEventListener(ImageEvent.IMAGE_LOADED, onImageLoaded);
			_loadCount++;
			if(_loadCount == _numImages) EventCentre.instance.dispatch(new ApplicationEvent(ApplicationEvent.UPDATE, "all_images_loaded"));
			else loadImage();
		}
		
		/**
		 * Singleton 
		 */		
		static private var _instance:ImageManager;
		static public function get instance():ImageManager
		{
			if(!_instance) _instance = new ImageManager();
			return _instance;
		}
	}
}